package com.jxsd.edu.cn.struts2.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;


public class DoCkAction 
{
	//文件
 	private     File  upload;
    private   String  uploadContentType;
    private   String  uploadFileName;
    private   String  savePath;
    
    
    /**
	    * 处理CK文件上传
	 * @throws Exception 
	    * */
	   public  void  doCk() throws Exception
	   {
		   String  fosPath=null;
		   fosPath=doUpload();
		   HttpServletRequest  request=ServletActionContext.getRequest();
		   String callback = request.getParameter("CKEditorFuncNum");  
		   HttpServletResponse  response=ServletActionContext.getResponse();
	       PrintWriter out=response.getWriter();
		    out.println("<script>window.parent.CKEDITOR.tools.callFunction('"
					+ callback + "','" + fosPath  + "','');</script>");
		    System.out.print("fosPath="+fosPath);
	   }
	   
	   /**
	    * hander  the  upload  file
	 * @throws FileNotFoundException 
	    * */
	   private  String  doUpload() throws Exception
	   {
		   String  fosPath=null;
		// 对于上传文件的存放地址来建立一个输出流
			fosPath=getSavePath()+"/"+ System.currentTimeMillis()
				+ uploadFileName.substring(uploadFileName.lastIndexOf("."),
						uploadFileName.length());
			
			 
	        String path = ServletActionContext.getServletContext()     
	                .getRealPath("/")+fosPath;
			
		   FileOutputStream fos = new FileOutputStream(path);
		   FileInputStream fis = new FileInputStream(getUpload());
		   byte[] buffer = new byte[1024];
		   int len = 0;
		   while ((len = fis.read(buffer)) > 0)
		   {
		    fos.write(buffer , 0 , len);
		   }
		   
		   fis.close();
		   fos.close();
		   
		   return  fosPath;
	   }
    
    
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String getSavePath() {
		return savePath;
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}
}
